package com.psct.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.psct.Constant;
import com.psct.R;
import com.psct.ThreadPool;
import com.psct.bean.CriRes;
import com.psct.bean.Criticism;
import com.psct.bean.UserAccount;
import com.psct.social.UserAccountManager;
import com.psct.web.HttpUtil;

/**
 * 评论列表
 * @author zjingchuan
 *
 */
public class CriticismFragment extends SherlockListFragment{
	CriAdapter mAdapter;
	List<Criticism> dataList;
	String mCurFilter;
	private int textId;
	private Handler handler  = new Handler () {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MESSAGE_LOAD_DONE:
				mAdapter.notifyDataSetChanged();
				setListShown(true);
				break;
			}
		}
		
	};
	/**
	 * 工厂方法
	 * @param 
	 * @return
	 */
	public static CriticismFragment newInstance(int bookId) {
		
		Bundle bundle = new Bundle();
		bundle.putInt(Constant.TEXT_ID, bookId);
		CriticismFragment f = new CriticismFragment();
		f.setArguments(bundle);
		return f;
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// 如果没有任何内容，提示
		setEmptyText("此课本还没有人留下记忆，你可以做第一个留下记忆的人，请点击下方的按钮开始。");
		// 是否需要在动作条显示菜单
		setHasOptionsMenu(true);
		
		this.getListView().setBackgroundResource(R.drawable.bg);
		this.getListView().setCacheColorHint(android.R.color.transparent);
		dataList = new ArrayList<Criticism>();
		// 创建一个空的adapter
		mAdapter = new CriAdapter();
		setListAdapter(mAdapter);
		// 开始显示圆形进度条
		setListShown(false);
		// 加载数据
		textId = this.getArguments().getInt(Constant.TEXT_ID);
		getData(textId);
	}

	/**
	 * 开启一个线程 去获取数据
	 * 
	 * @param curIndex
	 *            当前课本的下标
	 */
	private void getData(final int textId) {
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				CriRes res = new HttpUtil(getActivity()).getCriticism(textId);
				if(res!=null) {
					if(res.res==0) {
						dataList.addAll(res.criticismList);
						handler.sendEmptyMessage(Constant.MESSAGE_LOAD_DONE);
					}
				}else {
					handler.sendEmptyMessage(Constant.MESSAGE_NET_ERR);
				}
			}
		});
		
//		PSCTDatabase db = new PSCTDatabase(this.getActivity());
//		//TODO 先从数据库获取，显示出来；然后去读取网络数据，保存在数据库；通知更新；

	}

	/**
	 * 创建菜单
	 */
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		SearchView searchView = new SearchView(((SherlockFragmentActivity) getActivity())
//				.getSupportActionBar().getThemedContext());
//		searchView.setQueryHint("输入课文标题");
//		menu.add("搜索")
//				.setIcon(R.drawable.abs__ic_search_api_holo_light)
//				.setActionView(searchView)
//				.setShowAsAction(
//						MenuItem.SHOW_AS_ACTION_IF_ROOM
//								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
	}

	/**
	 * 列表点击后的事件处理
	 */
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		Log.i("FragmentComplexList", "Item clicked: " + id);
		
	}
	
	/**
	 * 适配器
	 */
	public class CriAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return dataList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if(convertView==null) {
				convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_criticism, null);
				viewHolder = new ViewHolder();
				convertView.setTag(viewHolder);
				viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
				viewHolder.tvOthers = (TextView) convertView.findViewById(R.id.tv_others);
				viewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_userName);
			}else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			Criticism c = dataList.get(position);
			viewHolder.tvContent.setText(c.content);
			//String date = new SimpleDateFormat("留于yyyy年MM月dd日").format(dataList.get(position).date);
			viewHolder.tvOthers.setText(c.date);
			String name = c.user;
			UserAccount account = UserAccountManager.getInstance().getUser(getActivity());
			if(account!=null&&account.userName.equals(c.user)) {
				name="自己";
			}
			viewHolder.tvUserName.setText(name+" 留于：");
			
			return convertView;
		}
		
		class ViewHolder{
			TextView tvContent,tvOthers,tvUserName;
		}
	}

	public void upLoad(Criticism c) {
		dataList.add(0, c);
		mAdapter.notifyDataSetChanged();
	}
}
